﻿using FastExecutor.Base.Design;
using FastExecutor.Base.Util;
using FastExecutor.ORG.Entity;
using FastIOC.Annotation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastExecutor.ORG.DB
{
    public class DB_Column : FastTemplateDB<Frame_TableStruct>
    {
        [AutoWired]
        private DB_Table @DB_Table;
        public override void Insert(Frame_TableStruct Entity)
        {
            Frame_Table Table = @DB_Table.FindOne(Entity.TableGuid);
            if ( Entity.RowGuid == null)
            {
                Entity.RowGuid = CommonUtil.CreateCommonGuid();
            }
            Entity.AddDate = DateTime.Now;
            Entity.IsSys = 0;
            string DDLSQL = string.Empty;
            switch (Entity.FieldType)
            {
                case "nvarchar":
                    DDLSQL = string.Format("{0}({1})", Entity.FieldType, Entity.FieldLength);
                    break;
                case "numeric":
                    DDLSQL = string.Format("{0}(10,{1})", Entity.FieldType, Entity.FieldLength);
                    break;
                case "blob":
                case "longtext":
                case "int":
                case "datetime":
                    DDLSQL = string.Format("{0}", Entity.FieldType);
                    break;
            }
            string FinalDDLSQL = string.Format("ALTER TABLE {0} ADD {1} {2}",
                    Table.SQLTableName, Entity.SQLFieldName, DDLSQL);
            @DBUtil.ExecuteSQL(FinalDDLSQL);
            base.Insert(Entity);
        }

        public override void Update(Newtonsoft.Json.Linq.JObject JsonEntity)
        {
            base.Update(JsonEntity);
        }

        public override void BatchDelete(List<string> KeyGuidList)
        {
            foreach (string KeyGuid in KeyGuidList)
            {
                Frame_TableStruct Column = FindOne(KeyGuid);
                Frame_Table Table = @DB_Table.FindOne(Column.TableGuid);
                string DDLSQL = string.Format("ALTER TABLE {0} DROP COLUMN {1}",
                Table.SQLTableName, Column.SQLFieldName);
                @DBUtil.ExecuteSQL(DDLSQL);
            }
            base.BatchDelete(KeyGuidList);
        }
    }
}
